<template>
  <!-- H5端地图容器 -->
  <!-- #ifdef H5 -->
  <div id="map-container" class="map"></div>
  <!-- #endif -->
  
  <!-- 非H5端提示 -->
  <!-- #ifndef H5 -->
  <view class="tip">地图功能仅支持H5端</view>
  <!-- #endif -->
</template>

<script setup>
import { onMounted, onUnmounted } from 'vue'

// 高德地图Key（建议从环境变量读取）
const mapKey = '9adeb42c078637ee021c57b4f7021614'

let map = null

onMounted(() => {
  // #ifdef H5
  loadMapScript()
  // #endif
})

onUnmounted(() => {
  if (map) map.destroy()
})

// 动态加载高德地图JS
function loadMapScript() {
  if (window.AMap) {
    initMap()
    return
  }

  const script = document.createElement('script')
  script.src = `https://webapi.amap.com/maps?v=2.0&key=${mapKey}`
  script.onload = initMap
  document.head.appendChild(script)
}

// 初始化地图
function initMap() {
  map = new AMap.Map('map-container', {
    zoom: 15,  // 缩放级别
    center: [116.397428, 39.90923],  // 北京坐标
    viewMode: '2D'
  })

  // 添加标记点
  new AMap.Marker({
    position: [116.397428, 39.90923],
    map: map
  })
  
  // 添加缩放控件
    map.addControl(new AMap.ControlBar({
      showZoomBar: true,
      showControlButton: true
    }))
    
    // 添加比例尺
    map.addControl(new AMap.Scale())
}

// 暴露方法给父组件
defineExpose({
  setCenter: (lng, lat) => {
    if (map) map.setCenter([lng, lat])
  }
})
</script>

<style scoped>
.map {
  width: 100%;
  height: 80vh;
}
.tip {
  padding: 20px;
  text-align: center;
}
</style>